import express, { Request, Response, Router } from 'express';
import { PrismaClient } from '@prisma/client';
import { ResponseHelper } from '../utils/response';
import { authenticateToken, requireAdmin } from '../middleware/auth';

const router: Router = express.Router();
const prisma = new PrismaClient();

/**
 * 获取用户列表（分页）
 * GET /api/v1/users
 * 查询参数：
 * - page: 页码（默认1）
 * - limit: 每页数量（默认20）
 * - role: 角色筛选（可选：ADMIN, USER）
 */
router.get('/', authenticateToken, requireAdmin, async (req: Request, res: Response) => {
  try {
    const page = parseInt(req.query.page as string) || 1;
    const limit = parseInt(req.query.limit as string) || 20;
    const role = req.query.role as string | undefined;
    const skip = (page - 1) * limit;

    // 构建查询条件
    const where: any = {};
    if (role && (role === 'ADMIN' || role === 'USER')) {
      where.role = role;
    }

    // 并行查询数据和总数
    const [users, total] = await Promise.all([
      prisma.user.findMany({
        where,
        select: {
          id: true,
          openid: true,
          unionid: true,
          username: true,
          nickname: true,
          avatarUrl: true,
          role: true,
          createdAt: true,
          updatedAt: true
        },
        skip,
        take: limit,
        orderBy: {
          createdAt: 'desc'
        }
      }),
      prisma.user.count({ where })
    ]);

    ResponseHelper.paginated(
      res,
      users,
      {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit)
      },
      '用户列表获取成功'
    );
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ResponseHelper.serverError(res, '获取用户列表失败', error);
  }
});

/**
 * 获取用户详情
 * GET /api/v1/users/:id
 */
router.get('/:id', authenticateToken, requireAdmin, async (req: Request, res: Response) => {
  try {
    const id = parseInt(req.params.id);

    if (isNaN(id)) {
      ResponseHelper.validationError(res, [{ field: 'id', message: '无效的用户ID' }]);
      return;
    }

    const user = await prisma.user.findUnique({
      where: { id },
      select: {
        id: true,
        openid: true,
        unionid: true,
        username: true,
        nickname: true,
        avatarUrl: true,
        role: true,
        createdAt: true,
        updatedAt: true
      }
    });

    if (!user) {
      ResponseHelper.notFound(res, '用户不存在');
      return;
    }

    ResponseHelper.success(res, user, '用户详情获取成功');
  } catch (error) {
    console.error('获取用户详情失败:', error);
    ResponseHelper.serverError(res, '获取用户详情失败', error);
  }
});

/**
 * 删除用户
 * DELETE /api/v1/users/:id
 */
router.delete('/:id', authenticateToken, requireAdmin, async (req: Request, res: Response) => {
  try {
    const id = parseInt(req.params.id);

    if (isNaN(id)) {
      ResponseHelper.validationError(res, [{ field: 'id', message: '无效的用户ID' }]);
      return;
    }

    // 检查用户是否存在
    const user = await prisma.user.findUnique({
      where: { id },
      select: { id: true, role: true }
    });

    if (!user) {
      ResponseHelper.notFound(res, '用户不存在');
      return;
    }

    // 禁止删除管理员账号
    if (user.role === 'ADMIN') {
      ResponseHelper.forbidden(res, '不允许删除管理员账号');
      return;
    }

    // 删除用户（级联删除关联数据）
    await prisma.user.delete({
      where: { id }
    });

    ResponseHelper.success(res, null, '用户删除成功');
  } catch (error) {
    console.error('删除用户失败:', error);
    ResponseHelper.serverError(res, '删除用户失败', error);
  }
});

export default router;
